use crate::api::EngineAPI;
use crate::config::GameConfig;
use anyhow::Result;
use std::io::{self, BufRead, Write};

pub struct JSBridge {
    api: EngineAPI,
}

impl JSBridge {
    pub fn new(config: GameConfig) -> Result<Self> {
        let api = EngineAPI::new(config)?;
        Ok(Self { api })
    }
    
    pub fn run(&mut self) -> Result<()> {
        let stdin = io::stdin();
        let mut stdin = stdin.lock();
        let mut stdout = io::stdout();
        
        // 注册JavaScript回调
        self.api.register_callback("custom_command", Box::new(|args| {
            println!("Custom command called with: {:?}", args);
            serde_json::json!({"result": "success"})
        }));
        
        // 主循环
        loop {
            // 提示输入
            write!(stdout, "GebEngine> ")?;
            stdout.flush()?;
            
            // 读取命令
            let mut command = String::new();
            stdin.read_line(&mut command)?;
            let command = command.trim();
            
            if command == "exit" {
                break;
            }
            
            // 解析命令
            let parts: Vec<&str> = command.splitn(2, ' ').collect();
            let (cmd, args_str) = if parts.len() == 2 {
                (parts[0], parts[1])
            } else {
                (command, "")
            };
            
            // 解析JSON参数
            let args = if args_str.is_empty() {
                serde_json::json!({})
            } else {
                serde_json::from_str(args_str).unwrap_or(serde_json::json!({}))
            };
            
            // 执行命令
            match self.api.execute_command(cmd, args) {
                Ok(result) => println!("Result: {}", serde_json::to_string(&result)?),
                Err(e) => eprintln!("Error: {}", e),
            }
        }
        
        Ok(())
    }
}